package com.kgc.zuulconfig;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;

/**
 * 创作人:孙榫笋
 * 创建时间: 2020/2/5 11:20
 * 定位：火星
 * 邮箱：Sun_DaiGeng@163.com
 */
public class PreFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        System.out.println("拦截成功");


        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("token");
        String requestUrl = request.getRequestURL().toString();
        if (requestUrl.split("/")[3].equals("p")) {
            return "pass";
        }

        if (token == null || token.equals("token")) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            context.setResponseBody("401");
            return "Access denied";
        }

        return "pass";
    }
}
